package com.hb.back.filter;

import com.alibaba.fastjson.JSON;
import com.hb.back.service.impl.EduAclUserServiceImpl;
import com.hb.back.token.Token;
import com.hb.common.vo.ResultVo;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.io.PrintWriter;

@AllArgsConstructor
public class TokenFile extends OncePerRequestFilter {
  EduAclUserServiceImpl aclUserService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
       String token =request.getHeader("token");
       if (token!=null){
           try{
               Token.validate(token);
               String name=Token.getName(token);
               UserDetails userDetails=aclUserService.loadUserByUsername(name);
               UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(userDetails.getUsername(),userDetails.getPassword(),userDetails.getAuthorities());
               SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
           } catch (Exception e) {
               response.setCharacterEncoding("utf-8");
               PrintWriter writer = response.getWriter();
               writer.write(JSON.toJSONString(ResultVo.error(50014, "没传token", null)));
               e.printStackTrace();
           }
       }
        filterChain.doFilter(request,response);
    }
}
